package com.acme.iolab.filesend.nio;


import com.acme.iolab.filesend.FileClient;
import com.acme.iolab.filesend.IntToByteArrayConverter;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NIOFileClient extends FileClient {

    public NIOFileClient(String serverIp, int port) {
        super(serverIp, port);
    }

    @Override
    public void sendFile(String filePath) throws IOException {
        File myFile = new File(filePath);
        try (SocketChannel socketChannel = SocketChannel.open();
             FileChannel src = new FileInputStream(myFile).getChannel()) {

            socketChannel.connect(new InetSocketAddress(serverIp, port));
            long start = System.currentTimeMillis();
            System.out.println("Connected to server.");

            ByteBuffer buffer = ByteBuffer.allocate((int) myFile.length());
            int size = (int) myFile.length();
            ByteBuffer sizeBuffer = ByteBuffer.allocate(4);
            sizeBuffer.put(IntToByteArrayConverter.convert(size));
            sizeBuffer.flip();
            socketChannel.write(sizeBuffer);
            while (src.read(buffer) != -1) {
                buffer.flip();
                socketChannel.write(buffer);
                buffer.clear();
            }
            System.out.println("File sent");

            socketChannel.read(ByteBuffer.allocate(1000));
            System.out.println("File sent in: " + (System.currentTimeMillis() - start));
        }
    }
}
